import axios from 'axios';
import qs from 'qs';
import { showNotify } from 'vant';


const baseurl = "https://api.btclass.net";




//---------------------以下axios基本配置---------------------
export const requestAxios = axios.create({
  baseURL: baseurl,
  timeout: 1000
});
// 分别设置get和post请求头
requestAxios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
requestAxios.defaults.headers.get['K-Method'] = 'is-get-method';
requestAxios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
requestAxios.defaults.headers.post['K-Method'] = 'is-post-method';
// 统一设置
requestAxios.defaults.headers.common['K-User-Agent'] = 'shit111';



requestAxios.interceptors.request.use(
  config => {
    // 添加请求头等前置处理
    config.headers['Is-App'] = '1'
    return config
  },
  error => {
    // 请求错误处理
    console.log('Request Error:', error)
    return Promise.reject(error)
  }
)

requestAxios.interceptors.response.use(
  response => {
    console.log('response:', response)
    // 响应后处理
    if (response.status === 200) {
      if (response.data.code === 200) {
        return Promise.resolve(response.data.res)
      } else {
        handleCommonError(response.data)
        return Promise.resolve(response.data)
      }
    } else {
      handleCommonError(response.data)
      return Promise.reject(response.data)
    }
  },
  error => {
    console.log('Response Error:', error)
    handleNetError(error)
    return Promise.reject(error)
  }
)

//---------------------以下通用错误处理---------------------
function handleCommonError(error) {
  // console.log('业务请求错误' + error)
  if (error.code === 401) {

    showNotify({ type: 'danger', message: error.msg || '请先登录' });
    router.push('/login')
  } else {
    showNotify({ type: 'danger', message: error.msg });
  }
}

function handleNetError(error) {
  console.log(error)
  const msg = error.response.status + ' ' + error.response.data.message
  showNotify({ type: 'danger', message: msg });
}

//---------------------以下是基本请求封装方法---------------------
export function getApi(url, params) {
  if (params) {
    url = url + '?' + qs.stringify(params)
  }
  return requestAxios({
    method: 'get',
    url: url
  }
  )
}

export function postApi(url, data) {
  return requestAxios({
    method: 'post',
    url: url,
    data: data
  })
}

//---------------------以下是业务请求---------------------

export function loginApi(user) {
  return postApi('/api/user/login',)
}
